package net.j4love.mybatis.kit.plugin;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.InterceptorChain;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.Field;
import java.util.List;

public class InterceptorChains {

    public static void replaceInterceptorChain(Configuration conf , List<Interceptor> interceptors) {

        try {
            Field f = Configuration.class.getDeclaredField("interceptorChain");
            f.setAccessible(true);
            InterceptorChain newChain = new InterceptorChain();
            for (Interceptor interceptor : interceptors) {
                newChain.addInterceptor(interceptor);
            }
            f.set(conf , newChain);
        } catch (ReflectiveOperationException e) {
        }
    }

    public static List<Interceptor> getInterceptors(Configuration conf) {
        return getInterceptorChain(conf).getInterceptors();
    }

    private static InterceptorChain getInterceptorChain(Configuration conf) {

        try {
            Field f = Configuration.class.getDeclaredField("interceptorChain");
            f.setAccessible(true);
            return (InterceptorChain) f.get(conf);
        } catch (ReflectiveOperationException e) {

        }
        return null;
    }


}
